package com.zhaojiadi.spring.bean.definition;

import com.zhaojiadi.spring.bean.factory.DefaultUserFactory;
import com.zhaojiadi.spring.bean.factory.UserFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * 特殊的 Bean 实例化
 */
public class SpecialBeanInstantiationDemo {
    public static void main(String[] args) {
        //配置xml配置文件
        //启动spring 应用上下文
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/META-INF/special-bean-instantiation-context.xml");
        //通过ApplicationContext获取AutowireCapabkeBeanFactory
        AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();
        ServiceLoader<UserFactory> serviceLoader = beanFactory.getBean("userFactoryServiceLoader", ServiceLoader.class);
        System.out.println(serviceLoader);

//        displayServiceLoader(serviceLoader);

        demoServiceLoader();

        //创建UserFactory 对象，通过AutowireCapableBeanFactory
        DefaultUserFactory userFactory = beanFactory.createBean(DefaultUserFactory.class);
//        System.out.println(userFactory.createUser());

    }

    public static void demoServiceLoader(){
        ServiceLoader<UserFactory> serviceLoader = ServiceLoader.load(UserFactory.class, Thread.currentThread().getContextClassLoader());
        displayServiceLoader(serviceLoader);
    }

    private static void displayServiceLoader(ServiceLoader<UserFactory> serviceLoader){
        Iterator<UserFactory> iterator = serviceLoader.iterator();
        while(iterator.hasNext()){
            UserFactory userFactory = iterator.next();
            System.out.println(userFactory.createUser());
        }

    }


}
